﻿using System.Configuration;
using CommonHelper.Enum;
using CommonHelper.Model;
using CommonHelper.Server.CommonApi;
using CommonHelper.Utility;
using Newtonsoft.Json;

namespace CommonHelper.Server
{
    /// <summary>
    /// 发送微信模板消息服务
    /// </summary>
    public class SendTemplateMessageService
    {
        private static readonly string AppId = ConfigurationManager.AppSettings["AppId"];
        private static readonly string AppSecret = ConfigurationManager.AppSettings["AppSecret"];
        private const string MessageApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";

        /// <summary>
        /// 公众号发送模板消息
        /// </summary>
        /// <param name="templateId">模板ID</param>
        /// <param name="openId">微信openId</param>
        /// <param name="url">点击详情跳转路径</param>
        /// <param name="data"></param>
        /// <param name="accessToken"></param>
        public static bool SendMessage(string templateId, string openId, string url, object data)
        {
            var isSuccess = false;
            var accessToken = AccessTokenContainer.TryGetToken(AppId, AppSecret);

            //获取用户信息
            var userInfo = CommonApi.CommonApi.GetUserInfo(accessToken, openId);
            //判断用户是否关注公众号
            switch (userInfo.subscribe)
            {
                case 0:
                    break;
                default:
                    var sendUrl = string.Format(MessageApi, accessToken);
                    var msg = new TemplateMessageResponse
                    {
                        template_id = templateId,
                        touser = openId,
                        url = url,
                        data = data
                    };
                    //序列化实体为json
                    string json = JsonConvert.SerializeObject(msg, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

                    //调用消息发送接口
                    HttpClientHelper.PostResponse<TemplateMessageResult>(string.Format(sendUrl, accessToken), json);
                    isSuccess = true;
                    break;
            }
            return isSuccess;
        }
    }
}
